export class Credentials {
	constructor(bimServerApi) {
    this.bimServerApi = bimServerApi;
    
    this.div = document.createElement("div");
    this.div.classList.add("credentials");
    
    this.error = document.createElement("div");
    this.div.appendChild(this.error);
    
    this.login()
	}
	
	login() {
    let token = localStorage.getItem("token");
    if (token) {
    	return;
		}
    var username = "readonly@bimserver.com";    // 只读用户
    var password = "yRhsN9uIVp";
    // 账号信息再这里从服务端获取
    
		this.bimServerApi.login(username, password, () => {
			this.div.remove();
			localStorage.setItem("token", this.bimServerApi.token);
			this.resolve();
		}, (error) => {
			console.error(error);
			this.error.innerHTML = error.message;
		});
	}
	
	getCredentials() {
		return new Promise((resolve, reject) => {
			let token = localStorage.getItem("token");
			if (token) {
				this.bimServerApi.setToken(token, () => {
					resolve();
				}, () => {
					document.body.appendChild(this.div);
					this.resolve = resolve;
					localStorage.removeItem("token")
				});
			} else {
				document.body.appendChild(this.div);
				this.resolve = resolve;
			}
		});
	}
}
